require "autogen.NetworkMessageHandlerLibrary"

local pb = require "pb"
local protoString = ResourceLoader.LoadPb("autogen/PB_addressbook.pb")
pb.load(protoString)

PB_addressbook = {}

function PB_addressbook:RegisterAction(msgId, func)
    Debug.Log('开始注册')
    Debug.Log(func)
    if NetworkMessageHandler[msgId] then error('重复注册网络消息处理方法. ' .. '-' .. msgId) end
    NetworkMessageHandler[msgId] = func
end

------ Server 2 Client, decode --------
PB_addressbook.Person = 600
NetworkMessageDecoder[PB_addressbook.Person] = function(msgId, data) 
    local handler = NetworkMessageHandler[msgId]
    if not handler then print('网络消息没有注册处理方法.' .. '-' .. msgId); return end

     -- 从二进制数据解析出实际消息
    local msg = assert(pb.decode("tutorial.Person", data))
 
    -- 到上面都能成功，那么就差下面了
    handler(msg)
end

------ Client 2 Server, encode
PB_addressbook.PersonC2S = 601
NetworkMessageEncoder[PB_addressbook.PersonC2S] = function(src) 
    local data = pb.encode("tutorial.Person", src)
    return data
end

return PB_addressbook